<?php

namespace app\common\model;

use think\Model;

class Staff extends Model
{
    public function add_one($info){
        $info['display'] = 1;
        $info['inputtime'] = time();
        $info['password'] = md5($info['password']);

        return $this->insertGetId($info);
    }

    public function get_one($id,$field='*'){
        return $this->field($field)->where(['id'=>$id,'display'=>1])->find();
    }

    public function edit($id,$info){
        $info['updatetime'] = time();
        return $this->where(['id'=>$id,'display'=>1])->update($info);
    }

    static function getList($page,$pageSize,$search=[],$order = ['inputtime'=>'desc'],$field=['id','inputtime','name','phone','duties','authority']){
        $currentPage = $page;
        $page = ($page - 1) * $pageSize;
        $where = [];
        $info = self::field($field)->withSearch($where,$search )->where(['ins_id'=>$search['ins_id'],'display'=>1])->order($order)->limit($page,$pageSize)->select();
        $count = self::withSearch($where,$search )->where(['ins_id'=>$search['ins_id'],'display'=>1])->count();
        //todo 创建人名称
        foreach ($info as $infoKey => $infoValue){
            $info[$infoKey]['inputtime'] = date('Y-m-d H:i',$infoValue['inputtime']);
            $info[$infoKey]['do_authority'] = $infoValue['authority'] == 1?'一级':'二级';
        }
        $arr =  ['list'=>$info,'count'=>$count,'page'=>$currentPage,'pageSize'=>$pageSize];
        return $arr;
    }

    public function del($id){
        return $this->where(['id'=>$id,'display'=>1])->update(['display'=>0]);
    }

    public function get_one_from_phone($phone){
        return $this->where(['display'=>1,'phone'=>$phone])->find();
    }

    public function get_one_from_phone_unset_id($id,$phone){
        return  $this->where([['display' , '=',1],['phone','=',$phone],['id','<>',$id]])->find();
    }

    public function  ClientKey($txt, $operation = 'ENCODE', $key = 'pengzhuang')
    {
        $key = $key ? $key : md5($_SERVER['HTTP_USER_AGENT']);
        $txt = $operation == 'ENCODE' ? $txt : base64_decode($txt);
        $len = strlen($key);
        $code = '';
        for ($i = 0; $i < strlen($txt); $i++) {
        $k = $i % $len;
        $code .= $txt[$i] ^ $key[$k];
        }
        $code = $operation == 'DECODE' ? $code : base64_encode($code);
        return $code;
    }

}
